//
//  NTPTime.swift
//  PPKit
//
//  Created by gaoguang on 2020/9/27.
//  Copyright © 2020 scoresdata.net. All rights reserved.
//

/*
  示例：
 didFinishLaunchingWithOptions 中调用：
 NTPTime.shared.startNTP()
 NTPTime.shared.initNTPDate()
 
 网络监听中：
 reachability.whenReachable = {reachability in
     if reachability.connection != .unavailable && NTPTime.shared.isConnected == false {
         NTPTime.shared.initNTPDate()
     }
 }
 
 
 **/
import TrueTime

class NTPTime {
    static let shared = NTPTime()
    /// ntp时间获取
    var referenceTime: ReferenceTime?
    /// 是否获取成功
    var isConnected = false
    
    func startNTP() {
        TrueTimeClient.sharedInstance.start()
    }
    
    ///注册NTP时间
    func initNTPDate() {
        TrueTimeClient.sharedInstance.fetchIfNeeded { [weak self] (referenceTime) in
            self?.referenceTime = referenceTime
            self?.isConnected = true
        } failure: { [weak self] (error) in
            self?.isConnected = false
        }
    }
    
    /// 获取NTP时间->Date
    func ntpDate() -> Date {
        if let timer = referenceTime,isConnected {
            return timer.now()
        }else{
            return Date()
        }
    }

    /// 获取NTP时间戳
    /// - Returns: NTP时间戳
    func ntpTimestamp() -> TimeInterval {
        return ntpDate().timeIntervalSince1970
    }
    
    /// 指定时间与ntp时间的分钟差
    /// - Parameter time: 指定时间
    /// - Returns: 分钟差
    func diffMins(time:TimeInterval) -> Int{
        return Int((ntpTimestamp() - time)/60)
    }
}
